package com.xr.blackhoole.mvc.context;

import org.apache.commons.lang3.StringUtils;

/**
 * 上下文处理类
 */
public class BlackholeContextHolder {
    private final static InheritableThreadLocal<BlackholeContext> blackholeContextThreadLocal = new InheritableThreadLocal<>();

    /**
     * 链路穿透上下文标识
     */
    public static final String BLACKHOLE_REQUEST_MARK = "X-Wormhole-Header-Request";

    /**
     * 获取上下文
     *
     * @return
     */
    public static BlackholeContext getContext() {
        return blackholeContextThreadLocal.get();
    }

    /**
     * 获取上下文中的属性
     *
     * @param key
     * @return
     */
    public static String getProperty(String key) {
        BlackholeContext context = getContext();
        if (context != null) {
            return context.toString();
        }
        return null;
    }


    /**
     * 设置上下文
     *
     * @param context
     */
    public static void setContext(BlackholeContext context) {
        blackholeContextThreadLocal.set(context);
    }

    public static void setContext(String contextStr) {
        if (StringUtils.isNotEmpty(contextStr)) {
            setContext(new BlackholeContext(contextStr));
        }
    }

    /**
     * 将上下文进行失效
     */
    public static void invalidContext() {
        blackholeContextThreadLocal.remove();
    }
}
